<template>
  <div class="panel">
    <el-form
      :model="form"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
      label-position="left"
    >
      <div class="flexrowbetween mb_15">
        <span>请设置活动需要派发的奖项 </span>
        <div class="flex" v-if="rewordshow">
          <span class="f-14 c_000">安慰奖：</span>
          <el-switch
            :disabled="status == 1"
            v-model="isConsolation"
            active-color="#13ce66"
            inactive-color="#eee"
            :active-value="1"
            :inactive-value="0"
            @change="changeSwith"
          >
          </el-switch>
        </div>
      </div>
      <div class="flexcenter addbox">
        <i class="el-icon-circle-plus f-22 mr_10 commhover" @click="addTab"></i>
        <i class="el-icon-remove f-22 commhover" @click="removeTab"></i>
      </div>
      <el-tabs v-model="editableTabsValue" type="card" class="rewordtabs">
        <el-tab-pane
          v-for="(item, index) in form.reword"
          :key="item.name"
          :label="item.reword"
          :name="item.name"
        >
          <div class="rewordbox">
            <div class="flexrowbetween pt_10 borderb mt_10 mb_25">
              <div class="c_000">奖项设置</div>
            </div>
            <el-form-item
              label="奖项等级："
              :prop="'reword.' + index + '.level_name'"
              :rules="{
                required: true,
                message: '奖项等级不能为空',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="item.level_name"
                placeholder="请输入奖项等级"
                maxlength="24"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item
              label="奖项名称："
              :prop="'reword.' + index + '.draw_name'"
              :rules="{
                required: true,
                message: '奖项名称不能为空',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="item.draw_name"
                placeholder="请输入奖项名称"
                maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item
              label="奖项图片："
              :prop="'reword.' + index + '.photo'"
              :rules="{
                required: true,
                message: '请选择奖品图片',
                trigger: 'change',
              }"
            >
              <div class="flex aligncenter">
                <img
                  v-if="item.photo"
                  :src="domain + item.photo"
                  alt=""
                  class="photoimg mr_20"
                />
                <el-button type="primary" size="small" class="uploadbtn">
                  本地上传
                  <input
                    type="file"
                    name=""
                    accept="images/*"
                    :id="'draw' + index"
                    class="sloganimg commhover"
                    @change="upload($event, item, index)"
                  />
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="奖项类型：" prop="type">
              <el-radio-group v-model="item.type">
                <el-radio :label="1" :disabled='taskStatus>=1'>虚拟卡券</el-radio>
                <el-radio :label="2" :disabled='taskStatus>=1'>实物奖励</el-radio>
                <el-radio :label="3" :disabled='taskStatus>=1'>多抽x次</el-radio>
                <!-- <el-radio :label="4" :disabled='taskStatus>=1'>自定义链接</el-radio> -->
                <el-radio :label="5" :disabled='taskStatus>=1' v-if="item.name !== '99'"
                  >现金红包</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item
              label="跳转链接："
              v-if="item.type == 4"
              :prop="'reword.' + index + '.url'"
              :rules="{
                required: true,
                message: '奖项名称不能为空',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="item.url"
                placeholder="请输入中奖后的跳转链接"
                clearable
              ></el-input>
            </el-form-item> -->
            <el-form-item
              label="兑奖有效期："
              v-if="item.type !== 3"
              :prop="'reword.' + index + '.time'"
              :rules="{
                required: true,
                message: '兑奖有效期不能为空',
                trigger: 'change',
              }"
            >
            <!-- :rules="{
                required: true,
                message: '兑奖有效期不能为空',
                trigger: 'change',
              }" -->
              <el-date-picker
                v-model="item.time"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="多抽次数："
              v-if="item.type == 3"
              :prop="'reword.' + index + '.draw_num'"
            >
              <el-input-number
                v-model="item.draw_num"
                :min="0"
                label="多抽次数"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              v-if="item.name !== '99'"
              label="奖项数量："
              :prop="'reword.' + index + '.num'"
            >
              <div>
                <el-input-number
                  v-model="item.num"
                  label="奖项数量"
                ></el-input-number>
                <!-- {{item.sy_num}} {{typeof(item.sy_num)}} -->
                <span
                  v-if="taskStatus >= 1 && (item.sy_num || item.sy_num === 0)"
                  class="pl_15"
                  >当前剩余数量：{{ item.sy_num }}</span
                >
              </div>
              <div class="c_999">
                Tips:如果是已发布的奖项，该选项的值会在之前发布的数量上进行加减，如果需要减数量，可输入负值
              </div>
            </el-form-item>
            <template v-else>
              <el-form-item label="是否限制数量：" prop="is_limit">
                <el-radio-group v-model="item.is_limit">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="奖项数量："
                v-if="item.is_limit == 1"
                :prop="'reword.' + index + '.num'"
              >
                <el-input-number
                  v-model="item.num"
                  :min="0"
                  label="奖项数量"
                ></el-input-number>
              </el-form-item>
            </template>
            <el-form-item
              label="中奖金额："
              v-if="item.type == 5"
              :prop="'reword.' + index + '.coin'"
              :rules="{
                required: true,
                message: '请输入中奖金额',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="item.coin"
                placeholder="请输入中奖金额"
                maxlength="10"
                clearable
                type="number"
              ></el-input>
            </el-form-item>
            <template v-if="item.type == 1 || item.type == 2">
              <div class="flexrowbetween pt_10 borderb mt_42 mb_25">
                <div class="c_000">兑奖设置</div>
              </div>
              <!-- <el-form-item label="兑奖方式：" v-if="item.type == 2" prop="way">
                <el-radio-group v-model="item.way">
                  <el-radio :label="1">上门取件</el-radio>
                  <el-radio :label="2">邮寄</el-radio>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item
                label="兑奖方式："
                v-if="item.type == 2"
                prop="is_cash"
              >
                <el-radio-group v-model="item.is_cash">
                  <el-radio :label="2">上门取件</el-radio>
                  <el-radio :label="1">邮寄</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="取件地址："
                v-if="item.type == 2&&item.is_cash == 2"
                prop="is_cash"
              >
                <el-input v-model="item.address" placeholder="请输入上门取件地址" />
              </el-form-item>
            </template>
            <el-form-item
              label="兑奖说明："
              prop="cash_msg"
              v-if="item.type == 1 || item.type == 2 || item.type == 5"
            >
              <Tinymce
                :msg="item.cash_msg"
                @msgBasic="msgBasic($event, item)"
              ></Tinymce>
            </el-form-item>
            <el-button @click="save" type="primary" :loading="saveloading">保存</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- <div class="flexcenter"> -->

      <!-- </div> -->
    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce/index.vue";
import { toChinesNum } from "@/utils/validate";
import { uploadPhoto } from "@/api/comm";
import { isOverSize } from "@/utils/validate";
import { mapActions, mapGetters } from "vuex";
import {
  drawEdit,
  taskInfo,
  comfortOpen,
  comfortClose,
  comfortEdit,
  comfortSave,
  drawSave,
} from "@/api/active";
export default {
  data() {
    return {
      rewordshow:true,
      status: 0,
      isConsolation: 0,
      editableTabsValue: "0",
      tabIndex: 3,
      statusList: [
        { name: "即抽开奖", id: 1 },
        { name: "定时开奖", id: 2 },
        { name: "满人开奖", id: 3 },
      ],
      form: {
        reword: [
          {
            reword: "奖项一",
            name: "0",
            draw_name: "",
            photo: "",
            level_name: "一等奖",
            type: 1,
            num: 1,
            draw_num: "", //多抽几次
            // draw_type:1,//兑奖方式(1线上、2线下)
            is_cash: 2, //兑奖方式（1邮寄，2上门自取）
            cash_msg: "",
            coin: "",
            time: "", //时间
            url:'',
            address:''
          },
          {
            reword: "奖项二",
            name: "1",
            draw_name: "",
            photo: "",
            level_name: "二等奖",
            type: 1,
            num: 1,
            draw_num: "", //多抽几次
            is_cash: 2, //兑奖方式（1邮寄，2上门自取）
            cash_msg: "",
            coin: "",
            time: "", //时间
            url:'',
            address:''
          },
          {
            name: "2",
            reword: "奖项三",
            draw_name: "",
            photo: "",
            level_name: "三等奖",
            type: 1,
            num: 1,
            draw_num: "", //多抽几次
            is_cash: 2, //兑奖方式（1邮寄，2上门自取）
            cash_msg: "",
            coin: "",
            time: "", //时间
            url:'',
            address:''
          },
        ],
      },
      saveloading: false,
      openDrawtype:1,
      originConfort:null,
      taskStatus:1,//任务状态
    };
  },
  components: {
    Tinymce,
  },
  props: {
    activeId: {
      default: "",
    },
    taskType: {
      default: "",
    },
  },
  watch: {
    // task:{
    //   handler: function(val) {
    //     console.log('val测试测试:',val)
    //     // this.redirect = route.query && route.query.redirect;
    //   },
    //   immediate: true,
    //   deep: true
    // }
    taskType: {
      handler: function (val) {
        console.log("val测试测试:", val);
        // this.redirect = route.query && route.query.redirect;
        this.openDrawtype = val
        this.clearComfortable()
      },
      // immediate: true,
      deep: true,
    },
  },
  created() {
    // this.openDrawtype = this.taskType
    this.getInfo();
    // console.log("---------", this.taskType);
  },
  computed: {
    ...mapGetters(["iframeUrl", "iphonekey"]),
  },
  methods: {
    ...mapActions(["setUrl"]),

    // changeType(){
    //   this.taskType2 = 
    // }

    getInfo() {
      // let preveditableTabsValue = this.editableTabsValue
      taskInfo({ id: this.activeId }).then((res) => {
        // 已发布的安慰奖和定时开奖不可编辑安慰奖
        this.status = res.data.task.status || res.data.task.type == 2;
        this.taskStatus = res.data.task.status 
        let draw = res.data.draw.filter((item) => item.status == 1);
        this.form.reword = draw.map((item, index) => {
          let params = {
            ...item,
            reword: "奖项" + toChinesNum(index + 1),
            name: index + "",
            time: item.startime&&item.endtime?[item.startime, item.endtime]:'',
          };
          if (this.taskStatus >= 1) {
            params.sy_num = params.num;
            params.num = "";
          }
          return params;
        });
        this.editableTabsValue = "0";
        this.originConfort = res.data.comfort
        // console.log('this.editableTabsValue',this.editableTabsValue)
        let comfort = res.data.comfort;
        this.isConsolation = comfort.status;
        if (comfort.status == 1) {
          this.form.reword.push({
            ...comfort,
            reword: "安慰奖",
            name: "99",
            // name:this.form.reword.length+'',
            time: [comfort.startime, comfort.endtime],
          });
        }
        console.log('reword:',this.form.reword);
      });
    },

    clearComfortable(){
      console.log('clearComfortable:',this.form.reword)
      if(this.openDrawtype!==1){
        this.rewordshow = false
        this.form.reword = this.form.reword.filter(
          (tab) => tab.reword !== "安慰奖"
        );
        console.log('this.form.reword2:',this.form.reword)
      }else{
        this.rewordshow = true
        let arr = this.form.reword.filter((tab) => tab.reword == "安慰奖")
        console.log('arr:',arr)
        if(!arr.length){
          this.form.reword.push({
            ...this.originConfort,
            reword: "安慰奖",
            name: "99",
            // name:this.form.reword.length+'',
            time: [this.originConfort.startime, this.originConfort.endtime],
          });
        }
        console.log('this.form.reword1:',this.form.reword)
      }
    },

    changeSwith(val) {
      if (val) {
        comfortOpen({ id: this.activeId })
          .then(() => {
            this.$message.success("开启成功");
            this.form.reword.push({
              name: "99",
              reword: "安慰奖",
              draw_name: "",
              photo: "",
              level_name: "安慰奖",
              type: 1,
              num: 1,
              is_limit: 1,
              cash_msg: "",
              time: "", //时间
              url:'',
              address:''
            });
          })
          .catch(() => {
            this.isConsolation = 0;
          });
      } else {
        comfortClose({ id: this.activeId })
          .then(() => {
            this.$message.success("关闭成功");
            this.form.reword = this.form.reword.filter(
              (tab) => tab.reword !== "安慰奖"
            );
          })
          .catch(() => {
            this.isConsolation = 1;
          });
      }
    },

    addTab() {
      let num = 10;
      if(this.isConsolation){ //如果包含安慰奖
        num = 11
      }
      if(this.form.reword.length>=num){
        this.$message.warning('奖项数量不能大于10')
        return
      }
      console.log("添加");
      let newTabName = this.form.reword.length + 1 + "";
      if (!this.isConsolation) {
        this.form.reword.push({
          reword: "奖项" + toChinesNum(newTabName),
          name: newTabName,
          draw_name: "",
          photo: "",
          level_name: toChinesNum(newTabName) + "等奖",
          type: 1,
          num: 1,
          cash_msg: "",
          draw_type: "",
          coin: "",
          time: "",
          url:'',
          address:''
        });
      } else {
        newTabName = this.form.reword.length + "";
        this.form.reword.splice(this.form.reword.length - 1, 0, {
          reword: "奖项" + toChinesNum(newTabName),
          name: newTabName,
          title: "",
          title: "",
          level_name: toChinesNum(newTabName) + "等奖",
          type: 1,
          num: 1,
          cash_msg: "",
          time: "",
          address:''
        });
        console.log("this.form.reword:", this.form.reword);
      }
      // this.editableTabsValue = newTabName;
      // console.log('editableTabsValue:',this.editableTabsValue)
    },

    removeTab() {
      let activeName = this.editableTabsValue;
      let targetName = this.editableTabsValue;
      let tabs = this.form.reword;
      let datalist = tabs.filter((item) => item.name !== "99");
      if (datalist.length == 1) {
        this.$message.warning("最后一个不能删除");
        return;
      }
      // if(tabs.length)
      datalist.forEach((tab, index) => {
        if (tab.name === targetName) {
          let nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
      this.editableTabsValue = activeName + "";
      let hasConfigtable = tabs.filter((item) => item.name == "99");
      let index = tabs.length - 1;
      if (hasConfigtable.length) {
        index = tabs.length - 2;
      }
      this.form.reword.splice(index, 1);
      // this.save()

      // console.log(this.form.reword)
      // let targetName = this.editableTabsValue;
      // let tabs = this.form.reword;
      // let activeName = this.editableTabsValue;
      // if(targetName == '99'){
      //   this.$message.warning('安慰奖不能删除，如果不需要安慰奖，请关闭显示安慰奖的按钮')
      //   return
      // }
      // tabs.forEach((tab, index) => {
      //   if (tab.name === targetName) {
      //     let nextTab = tabs[index + 1] || tabs[index - 1];
      //     if (nextTab) {
      //       activeName = nextTab.name;
      //     }
      //   }
      // });
      // this.editableTabsValue = activeName;
      // this.form.reword = tabs.filter((tab) => tab.name !== targetName);
    },

    upload(event, item, index) {
      var file = event.currentTarget.files[0];
      if (isOverSize(file.size, 5)) {
        this.$message.warning("图片大小不能超过5MB");
        return;
      }
      var formData = new FormData();
      formData.append("file", file);
      formData.append("type", "draw");
      uploadPhoto(formData).then((res) => {
        item.photo = res.data;
        this.$set(this.form.reword, index, item);
        // this.form.reword[index].photo = res.data
        console.log("this.form.reword:", this.form.reword);
        document.getElementById("draw" + index).value = null;
      });
    },

    transData() {
      let arr = [];
      this.form.reword
        .filter((item) => item.name !== "99")
        .forEach((item) => {
          let params = {
            level_name: item.level_name,
            draw_name: item.draw_name,
            photo: item.photo,
            type: item.type,
            num: item.num,
            cash_msg: item.cash_msg,
          };
          if (item.type !== 3) {
            params.startime = item.time[0];
            params.endtime = item.time[1];
          }
          if (item.type == 2) {
            params.is_cash = item.is_cash;
            params.draw_type = item.is_cash == 2 ? 1 : 2;
            params.address = item.address
          } else if (item.type == 3) {
            params.draw_num = item.draw_num;
          } else if (item.type == 4) {
            // params.draw_num = item.draw_num
            params.url = item.url
          } else if (item.type == 5) {
            params.coin = item.coin;
          }
          arr.push(params);
        });
      return arr;
    },

    transComfort(item) {
      let params = {
        level_name: item.level_name,
        draw_name: item.draw_name,
        photo: item.photo,
        type: item.type,
        num: item.num,
        cash_msg: item.cash_msg,
        is_limit: item.is_limit,
      };
      if (item.type !== 3) {
        params.startime = item.time[0];
        params.endtime = item.time[1];
      }
      if (item.type == 2) {
        params.is_cash = item.is_cash;
        params.draw_type = item.is_cash == 2 ? 1 : 2;
        params.address = item.address
      } else if (item.type == 3) {
        params.draw_num = item.draw_num;
      } else if (item.type == 4) {
        params.url = item.url
        // params.draw_num = item.draw_num
      } else if (item.type == 5) {
        params.coin = item.coin;
      }
      return params;
    },

    save() {
      console.log(this.form,this.status);
      this.$refs.ruleForm.validate(valid=>{
        if(!valid){
          this.$message.warning('还有必填选项未填写，请检查奖品设置')
          return
        }
        let params = {
          id: this.activeId,
          data: this.transData(),
        };
        console.log(params);
        this.saveloading = true;
        if (this.status == 1) {
          //已发布
          drawSave(params)
            .then((res) => {
              if (this.isConsolation) {
                let isconsform = this.form.reword.filter(
                  (item) => item.name == "99"
                );
                let params = {
                  id: this.activeId,
                  ...this.transComfort(isconsform[0]),
                };
                comfortSave(params).then((res) => {
                  this.saveSuccess();
                });
              } else {
                this.saveSuccess();
              }
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          //未发布
          drawEdit(params)
            .then((res) => {
              console.log("res:", res);
              if (this.isConsolation) {
                let isconsform = this.form.reword.filter(
                  (item) => item.name == "99"
                );
                let params = {
                  id: this.activeId,
                  ...this.transComfort(isconsform[0]),
                };
                console.log("isconsform:", params);
                comfortEdit(params)
                  .then((res) => {
                    this.saveSuccess();
                  })
                  .catch(() => {
                    this.saveloading = false;
                  });
              } else {
                this.saveSuccess();
              }
            })
            .catch(() => {
              this.saveloading = false;
            });
        }
      })
    },

    saveSuccess() {
      this.$message.success("设置成功");
      this.getInfo();
      this.saveloading = false;
      this.setUrl(this.iframeUrl);
    },
    // 测试
    msgBasic(parmas, item) {
      console.log("hell-:", parmas, item);
      item.cash_msg = parmas;
    },
  },
};
</script>
<style lang="scss" scoped>
.panel {
  position: relative;
}
.addbox {
  position: absolute;
  top: 46px;
  right: 0;
  z-index: 2;
}
.borderb {
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.rewordbox {
  height: calc(100vh - 332px);
  overflow-y: auto;
  padding: 0 10px;
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
    background: #c1c1c1;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
    border-radius: 10px;
    background: #ededed;
  }
}
// .panel_h {
//   height: calc(100vh - 239px);
//   overflow-y: auto;
//   padding-right: 12px;

//   &::-webkit-scrollbar {
//     /*滚动条整体样式*/
//     width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
//     height: 1px;
//   }
//   &::-webkit-scrollbar-thumb {
//     /*滚动条里面小方块*/
//     border-radius: 10px;
//     box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
//     background: #c1c1c1;
//   }
//   &::-webkit-scrollbar-track {
//     /*滚动条里面轨道*/
//     box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
//     border-radius: 10px;
//     background: #ededed;
//   }
// }
.line {
  height: 82px;
}
::v-deep label {
  font-weight: normal;
}
::v-deep .el-form-item__label {
  color: #000;
  font-size: 15px;
}
.uploadbtn {
  position: relative;
  .sloganimg {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    opacity: 0;
  }
}
.photoimg {
  width: 80px;
  height: 80px;
  border-radius: 5px;
}
.rewordtabs{
  ::v-deep .el-tabs__nav-wrap{
    width: calc(100% - 54px);
  }
}
</style>